In [1]:
import matplotlib
matplotlib.use('Agg')
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
Flexible Image Transport System (FITS) is an standard file format used to image and data storage in astronomy.
If you work in astronomy you will have to manipulate FITS files at some point in your career.
Fortunately, you can also use astropy
to manipulate those files.
Here we will focus on showing how to read an image from a FITS file. We follow the basic FITS tutorial provided in the astropy tutorial.
We won't cover how to read data tables or how to write data to FITS files.
First we download a sample fits file
In [2]:
from astropy.utils.data import get_pkg_data_filename
from astropy.io import fits
image_file = get_pkg_data_filename('tutorials/FITS-images/HorseHead.fits')
We will printo the information in the FITS file
In [3]:
fits.info(image_file)
In this example the HDU 0 is name of the HDU. It has two dimensions: (891,893) and stores integer numbers. This is an image. We can extract it as follows
In [4]:
image_data = fits.getdata(image_file, ext=0)
In [5]:
type(image_data) # this is a numpy array
Out[5]:
In [6]:
plt.figure(figsize=(10,10))
plt.imshow(image_data)
plt.colorbar()
Out[6]:
you can use slicing to plot image subsets
In [7]:
plt.imshow(image_data[:200,700:])
plt.colorbar()
Out[7]:
In [8]:
plt.figure()
plt.imshow(image_data[:200,500:])
plt.colorbar()
# You can plot other symbols on top of the image
x = [297]
y = [130]
plt.scatter(x,y, s=400, marker='o', facecolors='none', edgecolors='r')
Out[8]:
In [ ]:
In [ ]:
In the directory ../data
of this repository we have a couple of files from SDSS.
One of the stores an image (frame-g-003919-2-0056.fits.bz2
) and the other stores spectra spec-1379-53063-0310.fits
.
In the next notebook you will learn how to download SDSS data. In the meantime we will play with those files.
Let's inspect first the image file
In [15]:
SDSS_file = "../data/SDSS/frame-g-003919-2-0056.fits.bz2"
fits.info(SDSS_file)
In this case we have four HDUs. The image corresponds to the first HDU (see the dimensions!).
In [16]:
SDSS_data = fits.getdata(SDSS_file, ext=0)
In [17]:
plt.figure(figsize=(10,10))
plt.imshow(np.log10(SDSS_data)) # The image is in linear flux units. To see some features we plot it in log-scale
plt.colorbar()
Out[17]:
In [18]:
plt.figure(figsize=(10,10))
plt.imshow(np.log10(SDSS_data[0:400,750:1150])) # The image is in linear flux units. To see some features we plot it in log-scale
plt.colorbar()
Out[18]:
Let's inspect now the spectra file
In [20]:
SDSS_file = "../data/SDSS/spec-1379-53063-0310.fits"
fits.info(SDSS_file)
Here we have 6 HDUs. Look at the name of each HDU. COADD
is the HDU that we need
In [21]:
SDSS_data = fits.getdata(SDSS_file, ext=1)
In [22]:
SDSS_data
Out[22]:
In [23]:
# Here comes the spectrum
plt.plot(10**SDSS_data['loglam'], SDSS_data['FLUX'], )
Out[23]: